package com.gqh.weather.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gqh.weather.auth.UserContext;
import com.gqh.weather.domain.dto.MyPage;
import com.gqh.weather.domain.dto.PageRequest;
import com.gqh.weather.domain.dto.SchoolCreateRequest;
import com.gqh.weather.domain.dto.SchoolUpdateRequest;
import com.gqh.weather.domain.entity.School;
import com.gqh.weather.domain.entity.Account;
import com.gqh.weather.domain.enums.RoleEnum;
import com.gqh.weather.domain.enums.StudySectionEnum;
import com.gqh.weather.exception.BusinessException;
import com.gqh.weather.exception.Result;
import com.gqh.weather.mapper.SchoolMapper;
import com.gqh.weather.mapper.AccountMapper;
import com.gqh.weather.mapper.CityMapper;
import com.gqh.weather.util.PasswordUtil;
import com.gqh.weather.util.ValidationUtil;

import cn.dev33.satoken.stp.StpUtil;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * 学校管理服务类
 */
@Slf4j
@Service
public class SchoolService extends ServiceImpl<SchoolMapper, School> {

    private final AccountMapper accountMapper;
    private final CityMapper cityMapper;

    public SchoolService(AccountMapper accountMapper, CityMapper cityMapper) {
        this.accountMapper = accountMapper;
        this.cityMapper = cityMapper;
    }

    /**
     * 创建学校
     *
     * @param request   创建请求
     * @return 创建结果
     */
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> createSchool(SchoolCreateRequest request) {
        try {
            // 业务验证
            validateSchoolRequest(request);
            
            // 检查学校名称是否重复
            if (isSchoolNameExists(request.getName())) {
                return Result.error("学校名称已存在");
            }
            
            // // 1. 先创建account记录
            // Account account = new Account();
            // account.setPassword(PasswordUtil.encode(request.getPassword())); 
            // account.setUsername(request.getName());
            // account.setMobile(request.getContact_mobile());
            // account.setRole(RoleEnum.SCHOOL_ACCOUNT.getValue());
            // account.setType(1);
            // account.setCitycode(request.getCitycode());
            // account.setPid(StpUtil.getLoginIdAsInt());
            
            // boolean accountSaved = accountMapper.insert(account) > 0;
            // if (!accountSaved) {
            //     return Result.error("创建账号失败");
            // }
            
            // 2. 生成accountName
            // String accountName = "s" + account.getId();
            // account.setAccount(accountName);
            // accountMapper.updateById(account);
            
            // 3. 生成studySectionDesc
            // String studySectionDesc = generateStudySectionDesc(request.getStudy_section());
            
            // 4. 插入school记录
            School school = new School();
            school.setName(request.getName());
            school.setContact(request.getContact());
            school.setContactMobile(request.getContact_mobile());
            // school.setAccountId(account.getId());
            // school.setAccount(accountName);
            // school.setStudySection(request.getStudy_section());
            // school.setStudySectionDesc(studySectionDesc);
            school.setCitycode(request.getCitycode());
            school.setIfEnable(0); // 默认启用
            school.setIsDeleted(0); // 默认未删除
            
            // 保存学校
            boolean success = save(school);
            if (success) {
                return Result.success(null);
            } else {
                return Result.error("创建学校失败");
            }
            
        } catch (BusinessException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("创建学校失败", e);
            return Result.error("系统错误");
        }
    }

    /**
     * 更新学校信息
     *
     * @param school 学校更新请求
     * @return 更新结果
     */
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> updateSchool(SchoolUpdateRequest school) {
        try {
            if (school.getId() == null) {
                return Result.error("学校ID不能为空");
            }
            
            // 检查学校是否存在
            School existSchool = getById(school.getId().intValue());
            if (existSchool == null || existSchool.getIsDeleted() == 1) {
                return Result.error("学校不存在");
            }
            
            // 如果修改了学校名称，检查新名称是否已被其他学校使用
            if (StringUtils.hasText(school.getName()) && 
                !school.getName().equals(existSchool.getName())) {
                if (isSchoolNameExists(school.getName())) {
                    return Result.error("学校名称已存在");
                }
            }
            
            // 1. 先更新account记录
            // Account account = new Account();
            // account.setId(existSchool.getAccountId());
            // if (StringUtils.hasText(school.getPassword())) {
            //     account.setPassword(PasswordUtil.encode(school.getPassword()));
            // }
            // if (StringUtils.hasText(school.getContact_mobile()) && 
            //     !school.getContact_mobile().equals(existSchool.getContactMobile())) {
            //     account.setMobile(school.getContact_mobile());
            // }
            
            // // 只有当account对象有需要更新的字段时才执行更新
            // if (StringUtils.hasText(school.getPassword()) || 
            //     (StringUtils.hasText(school.getContact_mobile()) && 
            //      !school.getContact_mobile().equals(existSchool.getContactMobile()))) {
            //     accountMapper.updateById(account);
            // }
            
            // 2. 生成studySectionDesc
            // String studySectionDesc = generateStudySectionDesc(school.getStudy_section());
            
            // 3. 更新school记录
            School updateSchool = new School();
            updateSchool.setId(school.getId().intValue());
            updateSchool.setName(school.getName());
            // updateSchool.setStudySection(school.getStudy_section());
            // updateSchool.setStudySectionDesc(studySectionDesc);
            updateSchool.setCitycode(school.getCitycode());
            updateSchool.setContact(school.getContact());
            updateSchool.setContactMobile(school.getContact_mobile());
            
            boolean success = updateById(updateSchool);
            if (success) {
                return Result.success(null);
            } else {
                return Result.error("更新学校信息失败");
            }
            
        } catch (Exception e) {
            log.error("更新学校信息失败", e);
            return Result.error("系统错误");
        }
    }

    /**
     * 删除学校
     *
     * @param schoolId 学校ID
     * @return 删除结果
     */
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> deleteSchool(Integer schoolId) {
        try {
            School school = getById(schoolId);
            if (school == null || school.getIsDeleted() == 1) {
                return Result.error("学校不存在");
            }
            
            // TODO: 检查学校是否有关联的账号或其他数据，如果有则不能删除
            removeById(schoolId);
            
            return Result.success(null);

        } catch (Exception e) {
            log.error("删除学校失败", e);
            return Result.error("系统错误");
        }
    }

    /**
     * 分页查询学校列表
     *
     * @param pageRequest 分页请求
     * @param citycode    城市码（权限过滤）
     * @return 查询结果
     */
    public Result<MyPage<School>> getSchoolList(PageRequest<School> pageRequest, String citycode) {
        try {
            Page<School> page = pageRequest.toPage();
            
            LambdaQueryWrapper<School> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(School::getIsDeleted, 0);
            
            // 城市码权限过滤
            if (!StringUtils.hasText(citycode)) {
                citycode = UserContext.getCurrentUser().getCitycode();
            }

            // 处理城市码逻辑
            List<String> childCodes = new ArrayList<>();

            // 获取子区域代码
            childCodes.addAll(cityMapper.selectChildrenCodesByCode(citycode));
            childCodes.add(citycode);

            wrapper.in(School::getCitycode, childCodes);
            
            // 关键字搜索
            if (StringUtils.hasText(pageRequest.getKeyword())) {
                wrapper.and(w -> w.like(School::getName, pageRequest.getKeyword())
                                 .or().like(School::getContact, pageRequest.getKeyword())
                                 .or().like(School::getContactMobile, pageRequest.getKeyword()));
            }
            
            wrapper.orderByDesc(School::getId);
            
            Page<School> result = page(page, wrapper);
            MyPage<School> myPage = MyPage.fromMybatisPlusPage(result);
            return Result.success(myPage);
            
        } catch (Exception e) {
            log.error("查询学校列表失败", e);
            return Result.error("查询失败");
        }
    }

    /**
     * 获取所有学校列表（不分页）
     *
     * @param citycode 城市码（权限过滤）
     * @return 查询结果
     */
    public Result<List<School>> getAllSchoolList(String citycode) {
        try {
            LambdaQueryWrapper<School> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(School::getIsDeleted, 0)
                   .eq(School::getIfEnable, 0);
            
            // 城市码权限过滤
            if (StringUtils.hasText(citycode)) {
                wrapper.like(School::getCitycode, citycode);
            }
            
            wrapper.orderByDesc(School::getId);
            
            List<School> result = list(wrapper);
            return Result.success(result);
            
        } catch (Exception e) {
            log.error("获取所有学校列表失败", e);
            return Result.error("查询失败");
        }
    }

    /**
     * 获取学校详情
     *
     * @param schoolId 学校ID
     * @return 学校详情
     */
    public Result<School> getSchoolInfo(Integer schoolId) {
        try {
            School school = getById(schoolId);
            if (school == null || school.getIsDeleted() == 1) {
                return Result.error("学校不存在");
            }
            
            return Result.success(school);
            
        } catch (Exception e) {
            log.error("获取学校详情失败", e);
            return Result.error("查询失败");
        }
    }

    /**
     * 启用/禁用学校
     *
     * @param schoolId 学校ID
     * @param flag     状态标志：0启用 1禁用
     * @return 操作结果
     */
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> enableSchool(Integer schoolId, Integer flag) {
        try {
            if (flag == null || (flag != 0 && flag != 1)) {
                return Result.error("状态标志参数错误");
            }
            
            School school = getById(schoolId);
            if (school == null || school.getIsDeleted() == 1) {
                return Result.error("学校不存在");
            }
            
            school.setIfEnable(flag);
            boolean success = updateById(school);
            
            if (success) {
                return Result.success(null);
            } else {
                return Result.error("操作失败");
            }
            
        } catch (Exception e) {
            log.error("启用/禁用学校失败", e);
            return Result.error("系统错误");
        }
    }

    /**
     * 导出学校账号信息
     *
     * @param citycode 城市码
     * @return 导出结果（这里返回查询结果，实际应该返回Excel文件URL）
     */
    public Result<List<School>> exportSchoolAccounts(String citycode) {
        try {
            LambdaQueryWrapper<School> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(School::getIsDeleted, 0)
                   .eq(School::getIfEnable, 0);
            
            if (StringUtils.hasText(citycode)) {
                wrapper.like(School::getCitycode, citycode);
            }
            
            wrapper.orderByDesc(School::getId);
            
            List<School> schools = list(wrapper);
            
            // TODO: 生成Excel文件并上传到文件服务器，返回下载URL
            // 这里暂时返回数据列表
            
            return Result.success(schools);
            
        } catch (Exception e) {
            log.error("导出学校账号失败", e);
            return Result.error("导出失败");
        }
    }

    // ========== 私有方法 ==========

    /**
     * 验证学校创建请求
     */
    private void validateSchoolRequest(SchoolCreateRequest request) throws BusinessException {
        // if (!ValidationUtil.isValidMobile(request.getContact_mobile())) {
        //     throw new BusinessException("联系电话格式不正确");
        // }
        
        // if (!ValidationUtil.isValidCitycode(request.getCitycode())) {
        //     throw new BusinessException("城市码格式不正确");
        // }
        
        // 验证学段
//        if (!isValidStudySection(request.getStudy_section())) {
//            throw new BusinessException("学段参数错误，必须是1、2、3、4或其组合");
//        }
    }

    /**
     * 检查学校名称是否存在
     */
    private boolean isSchoolNameExists(String name) {
        LambdaQueryWrapper<School> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(School::getName, name)
               .eq(School::getIsDeleted, 0);
        return count(wrapper) > 0;
    }

//    /**
//     * 检查学校账号是否存在
//     */
//    private boolean isSchoolAccountExists(String account) {
//        LambdaQueryWrapper<School> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(School::getAccount, account)
//               .eq(School::getIsDeleted, 0);
//        return count(wrapper) > 0;
//    }

//    /**
//     * 检查联系电话是否存在
//     */
//    private boolean isMobileExists(String mobile) {
//        LambdaQueryWrapper<School> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(School::getContactMobile, mobile)
//               .eq(School::getIsDeleted, 0);
//        return count(wrapper) > 0;
//    }
//
//    /**
//     * 验证学段是否有效
//     */
//    private boolean isValidStudySection(String studySection) {
//        if (studySection == null || studySection.trim().isEmpty()) {
//            return false;
//        }
//
//        // 学段可以是单个数字（1、2、3、4）或者逗号分隔的组合（如：1,2,3）
//        String[] sections = studySection.split(",");
//        for (String section : sections) {
//            String trimmed = section.trim();
//            if (!trimmed.matches("^[1-4]$")) {
//                return false;
//            }
//        }
//
//        return true;
//    }
//
//    /**
//     * 生成学段描述
//     *
//     * @param studySection 学段值
//     * @return 学段描述
//     */
//    private String generateStudySectionDesc(String studySection) {
//        if (studySection == null || studySection.trim().isEmpty()) {
//            return "";
//        }
//
//        StringBuilder desc = new StringBuilder();
//        String[] sections = studySection.split(",");
//
//        for (int i = 0; i < sections.length; i++) {
//            String section = sections[i].trim();
//            if (i > 0) {
//                desc.append(",");
//            }
//            desc.append(StudySectionEnum.getDescription(section));
//        }
//
//        return desc.toString();
//    }
}